#include <lib/stdint.h>
#include <lib/stdio.h>
#include <lib/stdlib.h>
#include <lib/stddef.h>
#include <lib/assert.h>
#include <os/memcache.h>
#include <os/debug.h>
#include <driver/view/color.h>
#include <driver/view/hal.h>
#include <driver/view/section.h>

static LIST_HEAD(view_section_list_head);

static view_section_t *ViewSectionAlloc(int width, int height);
static void ViewSectionFree(view_section_t *section);

int ViewSectionInit()
{
    list_init(&view_section_list_head);
    return 0;
}

int ViewSectionExit()
{
    view_section_t *section, *next;
    list_traversal_all_owner_to_next_safe(section, next, &view_section_list_head, list)
    {
        ViewSectionDestroy(section);
    }
    return 0;
}

int ViewSectionClear(view_section_t *section)
{
    if (!section)
        return -1;
    memset(section->addr, 0, section->size);
    return 0;
}

view_section_t *ViewSectionCreate(int width, int height)
{
    view_section_t *section = ViewSectionAlloc(width, height);
    if (!section)
    {
        KPrint(PRINT_ERR "%s: create section failed!\n", __func__);
        return NULL;
    }
    if (ViewSectionOpen(section) < 0)
    {
        KPrint(PRINT_ERR "%s: open section failed!\n", __func__);
        return NULL;
    }
    memset(section->addr, 0, section->size);
    return section;
}

int ViewSectionDestroy(view_section_t *section)
{
    if (!section)
        return -1;
    if (ViewSectionClose(section) < 0)
        return -1;
    ViewSectionFree(section);
    return 0;
}

static view_section_t *ViewSectionAlloc(int width, int height)
{
    view_section_t *section = KMemAlloc(sizeof(view_section_t));
    if (!section)
        return -1;
    section->handle = -1;
    section->addr = NULL;
    section->width = width;
    section->height = height;
    section->size = width * height * sizeof(view_color_t);
    list_add_tail(&section->list, &view_section_list_head);
    return section;
}

static void ViewSectionFree(view_section_t *section)
{
    if (!section)
        return -1;
    list_del_init(&section->list);
    KMemFree(section);
}